﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using YLClient.YLServiceReference;
using YLClient.Util;
using System.Threading.Tasks;

namespace YLClient.UserControls
{
    /// <summary>
    /// Interaction logic for Item.xaml
    /// </summary>
    public partial class Item : UserControl
    {
        private Item()
        {
            InitializeComponent();
        }
        public Item(WorkItem i)
            : this()
        {
            item = i;
            labTemplate.Content = item.TemplateName;
            labTime.Content = item.Time.ToShortDateString();
            labUserName.Content = item.boyName + "&" + item.grilName;
            txtbStatus.Text = item.Status;
            if (item.Status != "正在上传" && item.Status != "待制作" && item.Status != "正在制作")
            {
                btnDownload.IsEnabled = true;
            }
        }
        private WorkItem item;
        Task task;
        UserServiceClient client;
        Guid guid;
        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            client = GlobalClass.DataContainer.Client;
            guid = GlobalClass.DataContainer.Guid;
            client.UpdatedWorkItemStatus(item, WorkItemStatus.Downloading, guid);

            //从配置文件中获取保存目录
            string dir = Properties.Settings.Default.ItemSaveDir;

            ClientAdapter clientAdapter = new ClientAdapter();
            clientAdapter.OnTransferFinish += new Action<bool>(clientAdapter_OnTransferFinish);
          //  clientAdapter.OnTransferFileError += new OnTransferFileErrorEventHandler(clientAdapter_OnTransferFileError);
            TaskFactory factory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
            task = factory.StartNew(() =>
            {
                clientAdapter.DownloadFile(item, dir);
            });
        }

        void clientAdapter_OnTransferFileError(string fileName, int index)
        {
            txtbStatus.Text = "下载失败请重试";
        }

        void clientAdapter_OnTransferFinish(bool hasErr)
        {
            if (hasErr == false)
            {
                txtbStatus.Text = "下载成功";
                var ret = client.UpdatedWorkItemStatus(item, WorkItemStatus.Downloaded, guid);
                Console.WriteLine(ret);
            }
        }

    }
}
